package com.rocksdata.mc.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;


import com.ctz.commonframe.constant.DeviceInfo;
import com.ctz.commonframe.ui.BaseFragment;
import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.ui.view.EmbeddedGridView;
import com.ctz.commonframe.ui.widget.AbsAdapter;
import com.ctz.commonframe.ui.widget.AdapterViewHolder;
import com.ctz.commonframe.utils.FullyLinearLayoutManager;
import com.ctz.commonframe.utils.GlideApp;
import com.ctz.commonframe.utils.Logger;
import com.ctz.commonframe.utils.RecycleViewDivider;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ShapeHintView;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.CampusAppManager;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.business.location.UnreadManager;
import com.rocksdata.mc.entity.AnnouncementInfo;
import com.rocksdata.mc.entity.BannerInfo;
import com.rocksdata.mc.entity.CampusAppInfo;
import com.rocksdata.mc.entity.NewsInfo2;
import com.rocksdata.mc.entity.UnreadCache;
import com.rocksdata.mc.ui.activity.AppManagerActivity2;
import com.rocksdata.mc.ui.adapter.BannerListAdapter;
import com.rocksdata.mc.ui.adapter.WidgetNewsRecyclerAdapter;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import q.rorbin.badgeview.QBadgeView;

/**
 * Created by 陈堂正 on 2016/11/24.
 */
@ContentView(R.layout.fragment_home_page2)
public class HomePageFragment2 extends BaseFragment {

    @ViewInject(R.id.vp_banner)
    private RollPagerView vpBanner;
    @ViewInject(R.id.layout_announcement)
    private LinearLayout layoutAnnoucement;
    @ViewInject(R.id.vf_announcement)
    private ViewFlipper vfAnnouncement;
    @ViewInject(R.id.eg_app)
    private EmbeddedGridView egApp;
    @ViewInject(R.id.rv_news)
    private RecyclerView rvNews;

    private List<CampusAppInfo> campusAppList;
    private AppGridAdapter appAdapter;

    private List<NewsInfo2> newsList;
    private WidgetNewsRecyclerAdapter newsAdapter;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        setupBannerView();
        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        rvNews.setNestedScrollingEnabled(false);
        rvNews.setLayoutManager(linearLayoutManager);
        rvNews.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.light_gray)));
        rvNews.setFocusable(false);
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void onVisible() {
        Logger.e("homepage onvisible");
        refreshDatas();
    }

    @Override
    protected void onInvisible() {
        if (vfAnnouncement != null)
            vfAnnouncement.stopFlipping();
    }

    private void setupBannerView(){
        vpBanner.setLayoutParams(new LinearLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, DeviceInfo.screenWidth / 2));
        vpBanner.setHintView(new RectShapeHintView(mContext, R.mipmap.ic_indicator_selected, R.mipmap.ic_indicator_normal));
        vpBanner.setPlayDelay(3000);
        vpBanner.setAnimationDurtion(500);
        List<BannerInfo> bannerList = new ArrayList<BannerInfo>();

        bannerList.add(new BannerInfo(R.drawable.banner1));
        bannerList.add(new BannerInfo(R.drawable.banner2));

        BannerListAdapter bannerListAdapter = new BannerListAdapter(mContext, bannerList);
        vpBanner.setAdapter(bannerListAdapter);
    }

    private class RectShapeHintView extends ShapeHintView {
        private int focusResId;
        private int normalResId;

        public RectShapeHintView(Context context, @DrawableRes int focusResId, @DrawableRes int normalResId) {
            super(context);
            this.focusResId = focusResId;
            this.normalResId = normalResId;
        }

        @Override
        public Drawable makeFocusDrawable() {
            Drawable drawable = getContext().getResources().getDrawable(focusResId);
            return drawable;
        }

        @Override
        public Drawable makeNormalDrawable() {
            Drawable drawable = getContext().getResources().getDrawable(normalResId);
            return drawable;
        }
    }

    private void refreshDatas() {
        getAnnouncementData();
        getAppData();
        getNewsData();
    }

    private void getAnnouncementData() {
        BusinessManager.getAnnouncementManager().getAnnouncementListRemote(1, null, null, new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if(isSuccess){
                    @SuppressWarnings("unchecked")
                    List<AnnouncementInfo> dataList = (List<AnnouncementInfo>) object;
                    List<AnnouncementInfo> list = new ArrayList<>();
                    for (AnnouncementInfo info: dataList) {
                        if (!info.isRead())
                            list.add(info);
                    }
                    if(list.size() > 0) {
                        layoutAnnoucement.setVisibility(View.VISIBLE);
                        vfAnnouncement.removeAllViews();
                        for (final AnnouncementInfo info: list) {
                            View contentView = LayoutInflater.from(mContext).inflate(R.layout.item_homepage_annoucement, null);
//                            View readFlag = contentView.findViewById(R.id.view_unread_flag);
                            TextView tvTitle = contentView.findViewById(R.id.tv_announcement_title);

//                            if(info.isRead()){
//                                readFlag.setVisibility(View.INVISIBLE);
//                            }else{
//                                readFlag.setVisibility(View.VISIBLE);
//                            }
                            tvTitle.setText(info.getTitle());

                            vfAnnouncement.addView(contentView);

                            contentView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    try {
                                        String url = "file:///android_asset/www/index.html?baseUrl="
                                                + URLEncoder.encode(BuildConfig.HOST, "UTF-8")
                                                + "&apiToken=" + UserInfoManager.getAccessToken()
                                                + "&userType=" + UserInfoManager.getCurrentUserType()
                                                + "&userId=" + UserInfoManager.getCurrentUserId()
                                                + "#/announcement/" + info.getNoticeCode();
                                        Intent intent = new Intent(mContext, WebViewActivity.class);
                                        intent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
                                        mContext.startActivity(intent);
                                        BusinessInterface.IAnnouncementManager manager = BusinessManager.getAnnouncementManager();
                                        if (manager != null)
                                            manager.setRead(info.getNoticeCode());
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                        if (vfAnnouncement.getChildCount() > 1)
                            vfAnnouncement.startFlipping();
                    } else {
                        layoutAnnoucement.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    private void getAppData () {
        BusinessManager.getApplicationManager().syncAppList(new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if (campusAppList == null)
                    campusAppList = new ArrayList<>();
                campusAppList.clear();
                if (isSuccess) {
                    List<CampusAppInfo> apps = (List<CampusAppInfo>) object;
                    campusAppList.addAll(apps);
                    if (appAdapter == null) {
                        appAdapter = new AppGridAdapter(mContext, campusAppList);
                        egApp.setAdapter(appAdapter);
                        egApp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (position == campusAppList.size()) {
                                    Intent intent = new Intent();
                                    intent.setClass(mContext, AppManagerActivity2.class);
                                    mContext.startActivity(intent);
                                }else if(position < campusAppList.size()){
                                    CampusAppInfo info = (CampusAppInfo) parent.getItemAtPosition(position);
                                    CampusAppManager.skipToChildApplication(mContext, info);
                                }
                            }
                        });
                    } else {
                        appAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private class AppGridAdapter extends AbsAdapter<CampusAppInfo> {

        private AppGridAdapter(Context context, List<CampusAppInfo> datas) {
            super(context, datas, R.layout.item_campus_app_grid);
        }

        @Override
        public int getCount() {
            return datas.size() + 1;
        }

        @Override
        public void convert(AdapterViewHolder holder, CampusAppInfo data) {
            ImageView unreadFlag = holder.getView(R.id.iv_app_control);
            ImageView icon = holder.getView(R.id.iv_app_icon);
            TextView name = holder.getView(R.id.tv_app_name);
            QBadgeView badgeView;
            if (data != null) {
                if (unreadFlag.getTag() == null) {
                    badgeView = new QBadgeView(context);
                    badgeView.bindTarget(unreadFlag);
                    badgeView.setBadgeGravity(Gravity.CENTER | Gravity.CENTER);
                    badgeView.setBadgeTextSize(10, true);
                    badgeView.setBadgePadding(2, true);
                    unreadFlag.setTag(badgeView);
                } else {
                    badgeView = (QBadgeView) unreadFlag.getTag();
                }

                UnreadCache cache = UnreadManager.getUnreadCache();
                if (cache != null) {
                    int unreadCount = cache.getUnreadCount(data.getCode());
                    if (unreadCount > 0) {
                        badgeView.setBadgeNumber(unreadCount);
                    } else {
                        badgeView.hide(false);
                    }
                } else {
                    badgeView.hide(false);
                }
            }

            if(holder.getPosition() == datas.size()){
                icon.setImageResource(R.mipmap.ic_app_all);
                name.setText("所有应用");
            }else if(holder.getPosition() < datas.size()){
                if(data != null) {
                    GlideApp.with(icon.getContext()).load(data.getIcon()).into(icon);
                    name.setText(data.getName());
                }
            }else{
                icon.setImageDrawable(null);
                name.setText("");
            }
            holder.getConvertView().setLayoutParams(new AbsListView.LayoutParams(
                    AbsListView.LayoutParams.MATCH_PARENT, DeviceInfo.screenWidth / 4));
        }
    }

    private void getNewsData () {

        BusinessManager.getNewsManager().getNewsListByTag(null, 1, new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if(newsList == null)
                    newsList = new ArrayList<>();
                newsList.clear();
                if(isSuccess){
                    @SuppressWarnings("unchecked")
                    List<NewsInfo2> list = (List<NewsInfo2>) object;
                    if(list != null && list.size() > 0) {
                        for(NewsInfo2 info: list){
                            if(!newsList.contains(info))
                                newsList.add(info);
                        }
                    }
                }

                if(newsAdapter == null) {
                    newsAdapter = new WidgetNewsRecyclerAdapter(mContext, newsList);
                    rvNews.setAdapter(newsAdapter);
                    newsAdapter.setOnItemClickListener(new WidgetNewsRecyclerAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(Object item) {
                            NewsInfo2 info = (NewsInfo2) item;
                            String url;
                            switch (info.getType()){
                                case NewsInfo2.NEWS_TYPE_VIDEO:
                                    url = "file:///android_asset/pages/video.html?id=" + info.getNewsCode();
                                    break;
                                default:
                                    url = "file:///android_asset/pages/news.html?id=" + info.getNewsCode();
                                    break;

                            }
                            try {
                                url = "file:///android_asset/www/index.html?baseUrl="
                                        + URLEncoder.encode(BuildConfig.HOST, "UTF-8")
                                        + "&apiToken=" + UserInfoManager.getAccessToken()
                                        + "&userType=" + UserInfoManager.getCurrentUserType()
                                        + "&userId=" + UserInfoManager.getCurrentUserId()
                                        + "#/news/" + info.getNewsCode();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            Intent intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
                            mContext.startActivity(intent);
                        }
                    });
                }else {
                    newsAdapter.notifyDataSetChanged();
                }
            }
        });
    }

}